//
//  contactTVC2.m
//  UIScrollView的快速使用
//
//  Created by hongfei tam on 2019/3/5.
//  Copyright © 2019 YQ05. All rights reserved.
//

#import "contactTVC2.h"
#import "MKConstant.h"
#import "InfoCell.h"
#import "serverTVCell.h"
#import "contactUsTVCell.h"

#import "network.h"

@interface contactTVC2 ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    UITableView *tableview;
    
    UIActivityIndicatorView *loadActivity;  //加载动画
    UIView *activityBg;
    
    NSIndexPath *cellIndex;
    NSArray *serverarray;
    
    int menuType;
}

@end

@implementation contactTVC2

- (void)viewDidLoad {
    [super viewDidLoad];
    
    tableview.dataSource = self;
    tableview.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone; //去掉tableView行分割线

    tableview.tableFooterView=[[UIView alloc]init]; //去掉tableView多余的空白行分割线
    tableview.backgroundColor = BGGRAYCOLOR;
    self.tableView.bounces = NO;  //ios-tableView禁止上下弹性或一个方向弹性
    self.view.backgroundColor  = BGGRAYCOLOR;
    
    serverarray = @[@"- 請選擇 -",@"抗衰老療程",@"營養管理計劃",@"DNA檢測",@"醫療檢測",@"進階性美容療程",@"度身訂造修身/體重管理"];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    
}


- (void)setMenutype:(int)Menutype {
    
    menuType = Menutype;
    NSLog(@"menuType %d",menuType);
    //#warning Incomplete implementation, return the number of sections
  
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    if (menuType == 1) {
        return 1;
    } else {
        return 3;
    }
    
}
// cell 指定的高度为300
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
        if (indexPath.row == 0 && menuType != 1) {
            return 170 ;
        }else if (indexPath.row == 1){
            return 500 ;
        }else if (indexPath.row == 2){ // if (indexPath.row == 2)
            return 550 ;
        }else{
            return 500 ;
        }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        
        if (menuType == 1) {
            //服务预约
            NSString *image = @"young_logo_180x40.png";//[dataSource objectAtIndex:indexPath.row];
            //promotionTVCell *cell = [promotionTVCell createCellWithTableView:tableView];
            
            serverTVCell *cell = [serverTVCell createCellWithTableView:tableView];
            NSString *protitle = @"22"; //常量定义
            
            NSMutableDictionary *protitledic = [[NSMutableDictionary alloc]init];
            [protitledic setValue:@"+852 2110 1218" forKey:@"phoneLabel"];
            [protitledic setValue:@"info@youngplus.com.hk" forKey:@"emailLabel"];
            [protitledic setValue:serverarray forKey:@"serverarray"];
            
            [cell loadData:image label:protitle andprotitledic:protitledic];
            cell .contentView .backgroundColor = BGGRAYCOLOR; //cell背景颜色
            
            cell.tag = 1;
            return cell;
        } else {
            NSString *image = @"young_logo_180x40.png";//[dataSource objectAtIndex:indexPath.row];
            //promotionTVCell *cell = [promotionTVCell createCellWithTableView:tableView];
            InfoCell *cell = [InfoCell createCellWithTableView:tableView];
            NSString *protitle = @"11"; //常量定义
            
            NSMutableDictionary *protitledic = [[NSMutableDictionary alloc]init];
            [protitledic setValue:@"+852 2110 1218" forKey:@"phoneLabel"];
            [protitledic setValue:@"info@youngplus.com.hk" forKey:@"emailLabel"];
            
            [cell loadData:image label:protitle andprotitledic:protitledic];
            cell .contentView .backgroundColor = BGGRAYCOLOR; //cell背景颜色
            return cell;
        }
        /**
         *  头部cell
         */
        
        
    }else  if (indexPath.row == 1) {
        /**
         *  表格cell
         */
        NSString *image = @"young_logo_180x40.png";//[dataSource objectAtIndex:indexPath.row];
        //promotionTVCell *cell = [promotionTVCell createCellWithTableView:tableView];
        
        serverTVCell *cell = [serverTVCell createCellWithTableView:tableView];
        NSString *protitle = @"22"; //常量定义
        
        NSMutableDictionary *protitledic = [[NSMutableDictionary alloc]init];
        [protitledic setValue:@"+852 2110 1218" forKey:@"phoneLabel"];
        [protitledic setValue:@"info@youngplus.com.hk" forKey:@"emailLabel"];
        [protitledic setValue:serverarray forKey:@"serverarray"];
        
        [cell loadData:image label:protitle andprotitledic:protitledic];
        cell .contentView .backgroundColor = BGGRAYCOLOR; //cell背景颜色
        
        cell.tag = 1;
        return cell;
       
    }else if (indexPath.row == 2) { //
        /**
         *  表格cell
         */
        contactUsTVCell *cell2 = [contactUsTVCell createCellWithTableView:tableView];
        
        NSString *image = @"faphone_BROWN.png";//[dataSource objectAtIndex:indexPath.row];
        NSString *protitle = @"聯繫我們"; //常量定义
        
        NSMutableDictionary *protitledic = [[NSMutableDictionary alloc]init];
        //        [protitledic setValue:@"+852 666" forKey:@"phoneLabel"];
        //        [protitledic setValue:@"info@youngplus.com.hk" forKey:@"emailLabel"];
        
        
        [protitledic setValue:serverarray forKey:@"serverarray"];
        
        NSArray *setLabelarr = @[@"姓名*",@"聯絡電話*",@"性別",@"查詢",@"信息"];
        [protitledic setValue:setLabelarr forKey:@"setLabelarr"];
        
        //        UIPickerView *serverPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(50, 190, 230, 160)];
        //        serverPickerView.delegate = self;
        //        serverPickerView.dataSource = self;
        //        [cell2 addSubview:serverPickerView];
        
        
        [cell2 loadData:image label:protitle andprotitledic:protitledic];
        cell2 .contentView .backgroundColor = BGGRAYCOLOR; //cell背景颜色
        //cell.tag = indexPath;
        return cell2;
    }else{
        
        
        /**
         *  文字cell
         */
        static NSString *cellID = @"reuseCell";
        UITableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (Cell == nil) {
            Cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        //UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        Cell.textLabel.text = @"hello";
        return Cell;
    }
    
    return nil;
    
    // Configure the cell...
    
    
}




-(void)loadingView{  //等待网络结果动画

    CGRect frame = CGRectMake(0, 0, 100, 100);
    //UIView *activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg.center = self.view.center;
    activityBg.backgroundColor = [UIColor grayColor];
    activityBg.alpha = 0.7;
    activityBg.layer.cornerRadius = 5.0;
    //[self.view addSubview:activityBg];
    [self.view addSubview:activityBg];

    //UIActivityIndicatorView *loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];

    loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadActivity.frame = CGRectMake(30, 30, 40, 40);
    [loadActivity sizeToFit];
    loadActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityBg addSubview:loadActivity];
    [loadActivity startAnimating];

}
-(void)stoploading{
    [loadActivity stopAnimating];
    [activityBg removeFromSuperview];
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

/// textFiled键盘遮盖
-(void)viewWillAppear:(BOOL)animated
{
    [self registerForKeyboardNotifications];
    
    //接收提交信息
    //服务预约
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(contactUsTVcellsendAction:) name:@"serverTVcellsend" object:nil];
    
    //联系我们
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(contactUsTVcellsendAction:) name:@"contactUsTVcellsend" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(contactUsBackAction:) name:@"contactUsBackAction" object:nil];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
  
        [[NSNotificationCenter defaultCenter]removeObserver:self name:@"serverTVcellsend" object:nil];
        
        
        //接受信息 广播
        [[NSNotificationCenter defaultCenter]removeObserver:self name:@"contactUsTVcellsend" object:nil];
        
        //接受信息 广播 发送成功信息
        [[NSNotificationCenter defaultCenter]removeObserver:self name:@"contactUsBackAction" object:nil];

}
- (void)registerForKeyboardNotifications {
    NSLog(@"registerForKeyboardNotifications");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
}


- (void)textFieldDidBeginEditing:(UITextField *)textField {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textField.superview.superview];
    cellIndex = indexPath;
    NSLog(@"indexPath %@",indexPath);
}

#pragma mark 监听文本框


-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    NSIndexPath *myIndex = [tableview indexPathForCell:(UITableViewCell*)[[textField superview]superview]];

    NSLog(@"MyIndex.row = %ld",myIndex.row);
   // [_wifi_detali_tableView selectRowAtIndexPath:myIndex animated:NO scrollPosition:UITableViewScrollPositionNone];
    return YES;
}
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)textField.superview.superview];
//    cellIndex = indexPath;
//    NSLog(@"indexPath %@",indexPath);
//    return YES;
//}


- (void)keyboardWillShow:(NSNotification *)aNotification {
    NSLog(@"keyboardWillShow");
    NSDictionary* info = [aNotification userInfo];
    // 注意不要用UIKeyboardFrameBeginUserInfoKey，第三方键盘可能会存在高度不准，相差40高度的问题
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    // 修改滚动条和tableView的contentInset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, kbSize.height, 0);

    // 跳转到当前点击的输入框所在的cell
    [UIView animateWithDuration:0.2 animations:^{
        // [self.tableView scrollToRowAtIndexPath:_indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
        NSIndexPath *tbip = nil;//self->cellIndex; //现在为固定值，找办法修改
//        NSLog(@"tbip %@",tbip);
        [self.tableView scrollToRowAtIndexPath:tbip atScrollPosition:UITableViewScrollPositionTop animated:NO];
        //NSLog(@"animateWithDuration");
        //self.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);


    }];
}

- (void)keyboardWillBeHidden:(NSNotification *)aNotification {
    NSLog(@"keyboardWillBeHidden");
    self.tableView.contentInset = UIEdgeInsetsZero;
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsZero;
}

#pragma mark  接收提交信息
////接收提交信息
-(void)contactUsTVcellsendAction:(NSNotification*)notif{
    NSDictionary *dic = notif.userInfo;
    //    NSLog(@"s接受到的 字典。%@",dic);
    //    NSString *string = [dic valueForKey:@"name"]; //pagetitle
    //    NSLog(@"%@",string);
    [self contactUssendNetAction:dic];
}

-(void)showAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)successAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"點擊OK");
        [self gobackVC];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:okAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)gobackVC{
    dispatch_async(dispatch_get_main_queue(), ^{  //get 主线程
        //NSLog(@"currentThread %@ ",[NSThread currentThread]);
        //加载成功
        [self.navigationController popViewControllerAnimated:true];
        
    });
    
}


-(void)contactUssendNetAction:(NSDictionary*)dic{
    
    
    
    NSString *username = [dic valueForKey:@"name"]; //pagetitle
    NSString *userphone = [dic valueForKey:@"phone"]; //pagetitle
    NSString *usersex = [dic valueForKey:@"sex"]; //pagetitle
    NSString *service = [dic valueForKey:@"servertiem"]; //pagetitle
    NSString *action = [dic valueForKey:@"action"]; //pagetitle
    //NSLog(@"%@",username);
    
    
    // 正则
    if ([username containsString:@"#"] || [username containsString:@"$" ] || [username containsString:@"%"]) {
        [self showAlert:@"警告！" message: @"包含非法字符！"];
    }else if (userphone.length<6){
        //NSLog(@"userphone %@",userphone);
        [self showAlert:@"警告！" message: @"電話號碼长度不够！"];
    }else{
        [self loadingView];

        NSMutableDictionary *senddic = [[NSMutableDictionary alloc]init];
        [senddic setValue:username forKey:@"username"];
        [senddic setValue:userphone forKey:@"phone"];
        [senddic setValue:usersex forKey:@"sex"];
        [senddic setValue:service forKey:@"service"];
        [senddic setValue:action forKey:@"action"];
        
        if([action isEqualToString:@"contact"]){
            NSString *mess = [dic valueForKey:@"mess"]; //pagetitle
            [senddic setValue:mess forKey:@"msg"];
        }


        //[self showAlert:@"发送消息" message: @"发送消息成功"];
        network *sendNetWork = [[network alloc]init];


        [sendNetWork POSTrequest:YOUNGURL type:@"contactUs" senddic:senddic savekey:@"contactUs"];  //发送数据
        
    }
    
}

-(void)contactUsBackAction:(NSNotification*)notif{
    
    NSNumber *num = notif.object;
    int num2 = num.intValue;
    
    dispatch_queue_t q2 = dispatch_get_main_queue();  //get 主线程
    //    2 add Queue
    dispatch_async(q2, ^{
        [self stoploading];
       // NSLog(@"currentThread %@ ",[NSThread currentThread]);
        if (num2 == 1) {
            [self successAlert:@"消息" message: @"發送成功"];
        }else{
            [self showAlert:@"消息" message: @"發送失敗"];
        }
    });
    
    
}


-(void)dealloc{
    //接受信息 广播
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"serverTVcellsend" object:nil];
    
   
    //接受信息 广播
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"contactUsTVcellsend" object:nil];
    
    //接受信息 广播 发送成功信息
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"contactUsBackAction" object:nil];
}

@end
